<template>
  <div class="profile-container">
    <!-- 左侧导航栏 -->
    <div class="profile-nav">
      <ul class="nav-list">
        <li
            :class="{ active: currentTab === 'info' }"
            @click="currentTab = 'info'"
        >
          个人信息
        </li>
        <li
            :class="{ active: currentTab === 'orders' }"
            @click="currentTab = 'orders'"
        >
          我的订单
        </li>
        <li
            :class="{ active: currentTab === 'setting' }"
            @click="currentTab = 'setting'"
        >
          账户设置
        </li>
      </ul>
    </div>

    <!-- 右侧内容区 -->
    <div class="profile-content">
      <template v-if="currentTab === 'info'">
        <div class="user-info-card">
          <!-- 头像区域 -->
          <div class="avatar-upload-container">
            <div class="avatar-wrapper">
              <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像" class="user-avatar">
              <div v-else class="avatar-placeholder">
                <i class="el-icon-user"></i>
              </div>
              <div class="avatar-upload-overlay" @click="triggerFileUpload">
                <span>上传头像</span>
              </div>
            </div>
            <input type="file" ref="fileInput" accept="image/*" @change="handleFileUpload" style="display: none">
          </div>

          <div class="user-meta">
            <!-- 使用用户信息数据 -->
            <h3 class="user-name">{{ userInfo.username }}</h3>
            <p class="user-email">{{ userInfo.email }}</p>
            <div class="stats">
              <div class="stat-item">
                <span class="stat-value">2</span>
                <span class="stat-label">待收货</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">5</span>
                <span class="stat-label">收藏商品</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">3</span>
                <span class="stat-label">可用优惠券</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">836</span>
                <span class="stat-label">积分</span>
              </div>
            </div>
          </div>
        </div>
      </template>

      <template v-else-if="currentTab === 'orders'">
        <h2>我的订单</h2>
        <!-- 这里可根据实际接口数据渲染订单列表，先模拟结构 -->
        <div class="order-list">
          <div class="order-item" v-for="(order, index) in orderList" :key="index">
            <div class="order-info">
              <p>订单号：{{ order.orderNo }}</p>
              <p>商品总价：{{ order.totalAmount }} 元</p>
              <p>下单时间：{{ order.createTime }}</p>
              <p>订单状态：{{ order.status }}</p>
            </div>
            <div class="order-actions">
              <el-button type="text" @click="viewOrderDetail(order.orderId)">查看详情</el-button>
              <el-button type="primary" v-if="order.status === '待支付'" @click="payOrder(order.orderId)">立即支付</el-button>
            </div>
          </div>
          <div class="empty-tip" v-if="orderList.length === 0">
            暂无订单~
          </div>
        </div>
      </template>


      <!-- 账户设置模块 -->
      <template v-else-if="currentTab === 'setting'">
        <div class="setting-container">
          <h2>账户设置</h2>

          <!-- 修改邮箱 -->
          <div class="setting-item">
            <div class="setting-title">
              <h3>修改邮箱</h3>
            </div>
            <div class="setting-content">
              <p class="bound-email">{{ userInfo.email }}</p>
              <el-button type="primary" @click="openEmailEditDialog">修改邮箱</el-button>
            </div>
          </div>

          <!-- 修改手机 -->
          <div class="setting-item">
            <div class="setting-title">
              <h3>修改手机</h3>
            </div>
            <div class="setting-content">
              <p class="bound-phone">{{ userInfo.phone }}</p>
              <el-button type="primary" @click="openPhoneEditDialog">修改手机</el-button>
            </div>
          </div>

          <!-- 修改密码 -->
          <div class="setting-item">
            <div class="setting-title">
              <h3>修改密码</h3>
            </div>
            <div class="setting-content">
              <el-button type="primary" @click="openPasswordDialog">修改</el-button>
            </div>
          </div>

          <!-- 完善资料 -->
          <div class="setting-item">
            <div class="setting-title">
              <h3>完善资料</h3>
            </div>
            <div class="setting-content">
              <el-button type="primary" @click="openProfileDialog">完善</el-button>
            </div>
          </div>

          <!-- 意见反馈 -->
          <div class="setting-item">
            <div class="setting-title">
              <h3>意见反馈</h3>
            </div>
            <div class="setting-content">
              <el-button type="primary" @click="openFeedbackDialog">反馈</el-button>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>


    <!-- 地址弹窗：新增 / 修改复用 -->
  <el-dialog
      v-model="addressDialogVisible"
      :title="isEdit ? '修改地址' : '新增地址'"
      width="40%"
  >
    <el-form
        ref="addressForm"
        :model="form"
        :rules="rules"
        label-width="80px"
    >
      <el-form-item label="收货人" prop="receiver">
        <el-input v-model="form.receiver" placeholder="请输入收货人"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="fullAddress">
        <el-input
            v-model="form.fullAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="设为默认地址">
        <el-switch v-model="form.isDefault"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddressForm">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 删除确认对话框 -->
  <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
  >
    <span>确定要删除这个收货地址吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDeleteAddress">确认删除</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改邮箱弹窗 -->
  <el-dialog
      v-model="editEmailDialogVisible"
      title="修改邮箱"
      width="40%"
  >
    <el-form :model="editEmailForm">
      <el-form-item label="新邮箱">
        <el-input v-model="editEmailForm.email" placeholder="请输入新邮箱"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editEmailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditEmail">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改手机弹窗 -->
  <el-dialog
      v-model="editPhoneDialogVisible"
      title="修改手机"
      width="40%"
  >
    <el-form :model="editPhoneForm">
      <el-form-item label="新手机号">
        <el-input v-model="editPhoneForm.phone" placeholder="请输入新手机号"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editPhoneDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditPhone">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改密码弹窗 -->
  <el-dialog
      v-model="changePwdDialogVisible"
      title="修改密码"
      width="40%"
  >
    <el-form :model="changePwdForm">
      <el-form-item label="原密码">
        <el-input
            v-model="changePwdForm.oldPwd"
            type="password"
            placeholder="请输入原密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input
            v-model="changePwdForm.newPwd"
            type="password"
            placeholder="请输入新密码"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="changePwdDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmChangePwd">确认修改</el-button>
          </span>
    </template>
  </el-dialog>

  <!-- 完善资料弹窗 -->
  <el-dialog v-model="profileDialogVisible" title="完善资料" width="40%">
    <el-form :model="profileForm">
      <el-form-item label="用户名">
        <el-input v-model="profileForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="profileForm.gender">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker v-model="profileForm.birthday" type="date" placeholder="选择生日"></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="profileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProfile">确认完善</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 意见反馈弹窗 -->
  <el-dialog
      v-model="feedbackDialogVisible"
      title="意见反馈"
      width="40%"
  >
    <el-form :model="feedbackForm">
      <el-form-item label="反馈内容">
        <el-input
            v-model="feedbackForm.content"
            type="textarea"
            placeholder="请输入反馈意见"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="feedbackDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmFeedback">确认提交</el-button>
          </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted,watchEffect } from 'vue';
import { ElButton, ElDialog, ElForm, ElInput, ElTag, ElEmpty, ElSwitch, ElMessage, ElRadioGroup, ElRadio, ElDatePicker } from 'element-plus';
import { getUserInfo, updateUserInfo, changePassword } from '../api/user';
import { getUserOrderList } from '../api/order';

// 集中管理用户信息
const userInfo = reactive({
  id: '',
  username: '',
  email: '',
  phone: '',
  nickname: '',
  avatar: '',
  userType: '',
  status: '',
  gender: '',
  birthday: ''
});

const avatarUrl = ref('');
const uploadMessage = ref('');

// 页面加载时获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo();
    if (res.code === 0 && res.data) {
      Object.assign(userInfo, res.data);
      avatarUrl.value = userInfo.avatar || '';
    } else {
      ElMessage.error(res.msg || '获取用户信息失败');
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败');
  }
};

onMounted(() => {
  fetchUserInfo();
});

// 响应式数据 - 当前激活的tab
const currentTab = ref('info');
// 模拟订单数据（后续替换为接口请求）
const orderList = ref([]);
const orderTotal = ref(0);
const orderPageNum = ref(1);
const orderPageSize = ref(10);

const fetchOrderList = async () => {
  try {
    const res = await getUserOrderList({
      pageNum: orderPageNum.value,
      pageSize: orderPageSize.value
    });
    if (res.code === 0 && res.data) {
      orderList.value = res.data.list || [];
      orderTotal.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || '获取订单列表失败');
    }
  } catch (e) {
    ElMessage.error('获取订单列表失败');
  }
};

// 模拟收藏商品数据

// 收货地址模块数据

// 地址弹窗相关

// 新增头像上传相关数据
const fileInput = ref(null);

// 触发文件选择
const triggerFileUpload = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 简单验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }

  // 预览图片并同步 userInfo.avatar
  const reader = new FileReader();
  reader.onload = (event) => {
    avatarUrl.value = event.target.result;
    userInfo.avatar = event.target.result;
    ElMessage.success('头像已更新');
  };
  reader.readAsDataURL(file);
};

// 订单模块方法
const viewOrderDetail = (orderId) => {
  // 可跳转到订单详情页，或弹窗展示
  ElMessage.info('查看订单详情功能待实现');
};

const payOrder = (orderId) => {
  ElMessage.info('支付功能待实现');
};

// 我的收藏模块方法

// 收货地址模块方法

// 修改邮箱相关
const editEmailDialogVisible = ref(false);
const editEmailForm = reactive({
  email: ''
});
const openEmailEditDialog = () => {
  editEmailForm.email = userInfo.email || '';
  editEmailDialogVisible.value = true;
};
const confirmEditEmail = async () => {
  if (!editEmailForm.email) {
    ElMessage.error('请输入新邮箱');
    return;
  }
  try {
    const res = await updateUserInfo({
      nickname: userInfo.nickname,
      avatar: userInfo.avatar,
      email: editEmailForm.email,
      phone: userInfo.phone
    });
    if (res.code === 0) {
      ElMessage.success('邮箱修改成功');
      editEmailDialogVisible.value = false;
      fetchUserInfo();
    } else {
      ElMessage.error(res.msg || '邮箱修改失败');
    }
  } catch (e) {
    ElMessage.error('邮箱修改失败');
  }
};

// 修改手机相关
const editPhoneDialogVisible = ref(false);
const editPhoneForm = reactive({
  phone: ''
});
const openPhoneEditDialog = () => {
  editPhoneForm.phone = userInfo.phone || '';
  editPhoneDialogVisible.value = true;
};
const confirmEditPhone = async () => {
  if (!editPhoneForm.phone) {
    ElMessage.error('请输入新手机号');
    return;
  }
  try {
    const res = await updateUserInfo({
      nickname: userInfo.nickname,
      avatar: userInfo.avatar,
      email: userInfo.email,
      phone: editPhoneForm.phone
    });
    if (res.code === 0) {
      ElMessage.success('手机号修改成功');
      editPhoneDialogVisible.value = false;
      fetchUserInfo();
    } else {
      ElMessage.error(res.msg || '手机号修改失败');
    }
  } catch (e) {
    ElMessage.error('手机号修改失败');
  }
};

// 修改密码相关
const changePwdDialogVisible = ref(false);
const changePwdForm = reactive({
  oldPwd: '',
  newPwd: ''
});
const openPasswordDialog = () => {
  changePwdDialogVisible.value = true;
};
const confirmChangePwd = async () => {
  if (!changePwdForm.oldPwd || !changePwdForm.newPwd) {
    ElMessage.error('请输入完整的原密码和新密码');
    return;
  }
  try {
    const res = await changePassword(changePwdForm.oldPwd, changePwdForm.newPwd);
    if (res.code === 0) {
      ElMessage.success('密码修改成功');
      changePwdDialogVisible.value = false;
      changePwdForm.oldPwd = '';
      changePwdForm.newPwd = '';
    } else {
      ElMessage.error(res.msg || '密码修改失败');
    }
  } catch (e) {
    ElMessage.error('密码修改失败');
  }
};

// 完善资料相关
const profileDialogVisible = ref(false);

// 使用计算属性实现双向绑定
const profileForm = reactive({
  get username() {
    return userInfo.username;
  },
  set username(value) {
    userInfo.username = value;
  },
  get gender() {
    return userInfo.gender;
  },
  set gender(value) {
    userInfo.gender = value;
  },
  get birthday() {
    return userInfo.birthday;
  },
  set birthday(value) {
    userInfo.birthday = value;
  }
});

// 监听tab切换到订单时拉取订单数据
watchEffect(() => {
  if (currentTab.value === 'orders') {
    fetchOrderList();
  }
});

const openProfileDialog = () => {
  profileDialogVisible.value = true;
};

const confirmProfile = async () => {
  try {
    const updateData = {
      nickname: userInfo.nickname,
      avatar: userInfo.avatar,
      email: userInfo.email,
      phone: userInfo.phone
    };
    const res = await updateUserInfo(updateData);
    if (res.code === 0) {
      ElMessage.success('资料更新成功');
      profileDialogVisible.value = false;
      fetchUserInfo();
    } else {
      ElMessage.error(res.msg || '资料更新失败');
    }
  } catch (e) {
    ElMessage.error('资料更新失败');
  }
};

// 意见反馈相关
const feedbackDialogVisible = ref(false);
const feedbackForm = reactive({
  content: ''
});
const openFeedbackDialog = () => {
  feedbackDialogVisible.value = true;
};
const confirmFeedback = () => {
  // 简单模拟提交，可自行扩展提示、清空内容等
  feedbackDialogVisible.value = false;
};
</script>

<style scoped>
.profile-container {
  display: flex;
  min-height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

/* 左侧导航栏样式 */
.profile-nav {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}
.nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.nav-list li {
  padding: 14px 20px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s;
}
.nav-list li:hover {
  background-color: #f8f8f8;
}
.nav-list li.active {
  background-color: #ffebe6;
  color: #ff6700;
  font-weight: bold;
}

/* 右侧内容区样式 */
.profile-content {
  flex: 1;
  padding: 20px;
}

/* 个人信息卡片样式 */
.user-info-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.avatar {
  margin-right: 20px;
}
.avatar-placeholder {
  width: 80px;
  height: 80px;
  background-color: #dcdcdc;
  border-radius: 50%;
}
.user-meta {
  display: flex;
  flex-direction: column;
}
.user-name {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 8px 0;
}
.user-email {
  color: #999;
  margin: 0 0 12px 0;
}
.stats {
  display: flex;
  gap: 20px;
}
.stat-item {
  text-align: center;
}
.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #ff6700;
  display: block;
}
.stat-label {
  color: #999;
  font-size: 12px;
}

/* 订单列表样式 */
.order-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e6e6e6;
}
.order-info p {
  margin: 4px 0;
  color: #333;
}
.order-actions {
  display: flex;
  gap: 10px;
}
.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

/* 收藏商品列表样式 */
.favorite-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.favorite-item {
  width: 200px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.favorite-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}
.favorite-name {
  font-weight: bold;
  margin: 0 0 8px 0;
}
.favorite-price {
  color: #ff6700;
  margin: 0 0 10px 0;
}

/* 新增头像上传样式 */
.avatar-upload-container {
  position: relative;
  margin-right: 20px;
}
.avatar-wrapper {
  position: relative;
}
.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}
.avatar-placeholder {
  width: 80px;
  height: 80px;
  background-color: #dcdcdc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  font-size: 12px;
}
.avatar-wrapper:hover .avatar-upload-overlay {
  opacity: 1;
}

/* 收货地址模块样式 */
.address-management {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.address-list {
  margin-top: 20px;
}

.address-item {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  transition: all 0.3s;
  position: relative;
}

.address-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.address-item.is-default {
  border-color: #409EFF;
}

.address-item.is-default::before {
  content: "默认地址";
  position: absolute;
  top: -10px;
  left: 20px;
  background-color: #409EFF;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.address-detail {
  margin-bottom: 15px;
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 10px;
}

/* 空状态样式 */
.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

/* 账户设置模块样式 */
.setting-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.setting-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.setting-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.bound-tag, .unbound-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.bound-tag {
  background-color: #409EFF;
  color: white;
}

.unbound-tag {
  background-color: #f0f0f0;
  color: #999;
}

.setting-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.bound-phone {
  color: #666;
  margin: 0;
}

/* 弹窗样式 */
.el-dialog__body {
  padding: 20px;
}
</style>